package com.doge.walknovel.business.login

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.doge.walknovel.analysis.*
import com.doge.walknovel.api.*
import com.doge.walknovel.api.model.LoginTokenInfo
import com.doge.walknovel.business.home.library.LibraryRepository
import com.doge.walknovel.core.account.AccountHelper
import com.doge.walknovel.core.account.AppUserViewModel
import com.doge.walknovel.core.account.FacebookUser
import com.doge.walknovel.core.account.GoogleUser
import com.doge.walknovel.core.base.LoadStatus
import com.doge.walknovel.push.PushHelper
import com.doge.walknovel.utils.*

const val PROFILE_TYPE_FACEBOOK = 1
const val PROFILE_TYPE_GOOGLE = 2

class LoginViewModel : ViewModel() {
    val loadingGoogle = MutableLiveData<LoadStatus>()
    val loadingFacebook = MutableLiveData<LoadStatus>()

    val success = MutableLiveData<Any?>()

    fun loginByGoogle(data: GoogleUser?, error: String?) {
        if (data == null) {
            analysisEvent(login_google_sdk_error)
            feedback(login_google_sdk_error, "", error ?: "")
            return
        }
        require(isMainThread())
        log("loginByGoogle uid ${data.uid} idToken ${data.idToken} displayName ${data.displayName} avatarUrl ${data.avatarUrl}")
        loadingGoogle.value = LoadStatus.LOADING

        api.loginByGoogle(
            data.uid, data.idToken, data.displayName, data.avatarUrl
        )
            .map(ApiResultMapTransformer())
            .subscribeOnIO()
            .observeOnMain()
            .subscribe(object : ObserverAdapter<LoginTokenInfo>() {
                override fun onNext(t: LoginTokenInfo) {
                    loadingGoogle.value = LoadStatus.SUCCESS
                    analysisEvent(login_google_success)
                    AccountHelper.updateUToken(t.token)
                    AppUserViewModel.get().requestSelfInfo {
                        PushHelper.check()
                        LibraryRepository.get().requestMyLib()
                    }
                    success.value = Any()
                    success.value = null 

                    analysisInitUser(t.memberId)

                    if (t.firstLoginFlag == 1) analysisRegister(PROFILE_TYPE_GOOGLE)
                    else analysisLogin(PROFILE_TYPE_GOOGLE)
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    loadingGoogle.value = LoadStatus.FAILURE
                    analysisEvent(login_google_api_error)
                    feedback(login_google_api_error, "", e.message ?: "")
                }
            })
    }

    fun loginByFacebook(data: FacebookUser?, error: String?) {
        if (data == null) {
            analysisEvent(login_facebook_sdk_error)
            feedback(login_facebook_sdk_error, "", error ?: "")
            return
        }
        require(isMainThread())
        log("loginByFacebook uid ${data.id} idToken ${data.accessToken} displayName ${data.nickname} avatarUrl ${data.avatarUrl}")
        loadingFacebook.value = LoadStatus.LOADING

        api.loginByFacebook(
            data.id, data.accessToken, data.nickname, data.avatarUrl
        )
            .map(ApiResultMapTransformer())
            .subscribeOnIO()
            .observeOnMain()
            .subscribe(object : ObserverAdapter<LoginTokenInfo>() {
                override fun onNext(t: LoginTokenInfo) {
                    loadingFacebook.value = LoadStatus.SUCCESS
                    analysisEvent(login_facebook_success)
                    AccountHelper.updateUToken(t.token)
                    AppUserViewModel.get().requestSelfInfo {
                        PushHelper.check()
                        LibraryRepository.get().requestMyLib()
                    }
                    success.value = Any()
                    success.value = null

                    analysisInitUser(t.memberId)

                    if (t.firstLoginFlag == 1) analysisRegister(PROFILE_TYPE_FACEBOOK)
                    else analysisLogin(PROFILE_TYPE_FACEBOOK)
                }

                override fun onError(e: Throwable) {
                    super.onError(e)
                    loadingFacebook.value = LoadStatus.FAILURE
                    analysisEvent(login_facebook_api_error)
                    feedback(login_facebook_api_error, "", e.message ?: "")
                }
            })
    }


    fun logout() {
        AccountHelper.updateUToken(null)
        AppUserViewModel.get().updateSelf(null)
        LibraryRepository.get().requestMyLib()
        clearAllNotification()
        api.signOut()
            .subscribeOnIO()
            .observeOnMain()
            .subscribe(object : ObserverAdapter<ApiResult<Any?>>() {
                override fun onNext(t: ApiResult<Any?>) {
                }
            })
    }
}